package com.mm.cloth;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.mm.cloth.adapter.MatchAdapter;
import com.mm.cloth.model.Clothes;
import com.mm.cloth.model.Match;

import java.util.ArrayList;
import java.util.List;

public class OutfitListActivity extends AppCompatActivity {

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView rvOutfits;
    private TextView tvEmpty;
    private MatchAdapter matchAdapter;
    private List<Match> outfitList = new ArrayList<>();
    
    // 分页相关变量
    private int currentPage = 1;
    private int pageSize = 6;
    private boolean isLoading = false;
    private boolean isLastPage = false;
    private View loadingFooter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_outfit_list);

        // 初始化所有视图和变量
        outfitList = new ArrayList<>();
        
        // 初始化视图
        initViews();
        
        // 设置工具栏
        setupToolbar();
        
        // 设置RecyclerView
        setupRecyclerView();
        
        // 加载数据
        loadOutfits(true);
    }

    private void initViews() {
        android.util.Log.d("OutfitListActivity", "初始化视图开始");
        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
        rvOutfits = findViewById(R.id.rvOutfits);
        tvEmpty = findViewById(R.id.tvEmpty);
        
        // 立即设置LayoutManager
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        rvOutfits.setLayoutManager(layoutManager);
        android.util.Log.d("OutfitListActivity", "设置LayoutManager完成: " + (rvOutfits.getLayoutManager() != null));
        
        loadingFooter = getLayoutInflater().inflate(R.layout.item_loading_footer, rvOutfits, false);

        // 设置下拉刷新
        swipeRefreshLayout.setOnRefreshListener(() -> loadOutfits(true));
        android.util.Log.d("OutfitListActivity", "初始化视图完成");
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("我的搭配");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    private void setupRecyclerView() {
        android.util.Log.d("OutfitListActivity", "设置RecyclerView开始");
        // 初始化适配器
        matchAdapter = new MatchAdapter(this, outfitList);
        
        // 获取已设置的LayoutManager
        GridLayoutManager layoutManager = (GridLayoutManager) rvOutfits.getLayoutManager();
        android.util.Log.d("OutfitListActivity", "获取LayoutManager: " + (layoutManager != null));
        
        if (layoutManager != null) {
            // 设置加载底部视图占据整行
            layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return matchAdapter.getItemViewType(position) == MatchAdapter.VIEW_TYPE_LOADING ? 2 : 1;
                }
            });
        }
        
        // 设置适配器
        rvOutfits.setAdapter(matchAdapter);
        android.util.Log.d("OutfitListActivity", "设置Adapter完成: " + (rvOutfits.getAdapter() != null));

        // 设置点击事件
        matchAdapter.setOnMatchClickListener(match -> {
            Intent intent = new Intent(this, MatchDetailActivity.class);
            intent.putExtra("match_id", match.getId());
            startActivity(intent);
        });
        
        // 添加滚动监听器
        rvOutfits.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                
                GridLayoutManager lm = (GridLayoutManager) recyclerView.getLayoutManager();
                if (lm == null) return;
                
                int visibleItemCount = lm.getChildCount();
                int totalItemCount = lm.getItemCount();
                int firstVisibleItemPosition = lm.findFirstVisibleItemPosition();
                
                if (!isLoading && !isLastPage) {
                    if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                            && firstVisibleItemPosition >= 0
                            && totalItemCount >= pageSize) {
                        loadMoreOutfits();
                    }
                }
            }
        });
        android.util.Log.d("OutfitListActivity", "设置RecyclerView完成");
    }

    private void loadOutfits(boolean isRefresh) {
        // 确保RecyclerView已正确设置
        ensureRecyclerViewSetup();
        
        if (isLoading && !isRefresh) return;
        
        isLoading = true;
        
        if (isRefresh) {
            currentPage = 1;
            isLastPage = false;
            outfitList.clear();
            matchAdapter.notifyDataSetChanged();
        }

        swipeRefreshLayout.setRefreshing(true);

        // 模拟网络请求延迟
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            // 加载前移除底部加载视图
            if (!isRefresh) {
                matchAdapter.removeLoadingFooter();
            }
            
            // 获取模拟数据
            List<Match> newOutfits = getSimulatedOutfits(currentPage);
            
            if (newOutfits.isEmpty()) {
                isLastPage = true;
                if (currentPage == 1) {
                    // 第一页就没有数据
                    updateEmptyView();
                } else {
                    Toast.makeText(this, "已加载全部搭配", Toast.LENGTH_SHORT).show();
                }
            } else {
                outfitList.addAll(newOutfits);
                matchAdapter.notifyDataSetChanged();
                
                // 如果不是最后一页，添加底部加载视图
                if (newOutfits.size() >= pageSize) {
                    matchAdapter.addLoadingFooter();
                } else {
                    isLastPage = true;
                }
            }

            // 更新UI状态
            swipeRefreshLayout.setRefreshing(false);
            isLoading = false;
            updateEmptyView();
        }, 1000);
    }
    
    // 确保RecyclerView已正确设置
    private void ensureRecyclerViewSetup() {
        if (rvOutfits == null) {
            rvOutfits = findViewById(R.id.rvOutfits);
        }
        
        if (rvOutfits.getLayoutManager() == null) {
            GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
            rvOutfits.setLayoutManager(layoutManager);
            android.util.Log.d("OutfitListActivity", "在loadOutfits中重新设置LayoutManager");
            
            // 如果适配器已经存在，重新设置SpanSizeLookup
            if (matchAdapter != null) {
                layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                    @Override
                    public int getSpanSize(int position) {
                        return matchAdapter.getItemViewType(position) == MatchAdapter.VIEW_TYPE_LOADING ? 2 : 1;
                    }
                });
            }
        }
        
        if (rvOutfits.getAdapter() == null && matchAdapter != null) {
            rvOutfits.setAdapter(matchAdapter);
            android.util.Log.d("OutfitListActivity", "在loadOutfits中重新设置Adapter");
        }
    }

    private void loadMoreOutfits() {
        if (isLoading || isLastPage) return;
        
        // 显示加载更多的提示
        Toast.makeText(this, "正在加载更多...", Toast.LENGTH_SHORT).show();
        
        currentPage++;
        loadOutfits(false);
    }

    private void updateEmptyView() {
        if (outfitList.isEmpty()) {
            tvEmpty.setVisibility(View.VISIBLE);
            rvOutfits.setVisibility(View.GONE);
        } else {
            tvEmpty.setVisibility(View.GONE);
            rvOutfits.setVisibility(View.VISIBLE);
        }
    }

    private List<Match> getSimulatedOutfits(int page) {
        List<Match> matches = new ArrayList<>();
        
        // 模拟分页，每页pageSize条数据
        // 假设总共有15条数据，分3页
        int totalItems = 15;
        int startIndex = (page - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, totalItems);
        
        // 如果超出范围，返回空列表
        if (startIndex >= totalItems) {
            return matches;
        }

        // 添加模拟数据
        for (int i = startIndex + 1; i <= endIndex; i++) {
            Match match = new Match();
            match.setId(i);
            match.setTitle("搭配 " + i);
            match.setDescription("这是搭配描述 " + i);
            match.setImageUrl("https://example.com/outfit" + i + ".jpg");
            match.setLikes(10 + i);
            match.setViews(50 + i * 2);
            match.setCategoryName(i % 2 == 0 ? "休闲" : "正式");
            match.setUserId(1);
            match.setUserName("用户001");
            
            // 添加衣物
            List<Clothes> clothesList = new ArrayList<>();
            clothesList.add(new Clothes(i, "衣物 " + i, String.valueOf(i % 4 + 1), "https://example.com/clothes" + i + ".jpg", "四季"));
            match.setClothesList(clothesList);
            
            matches.add(match);
        }

        return matches;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
} 